package com.boss.salary.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.IGenerateSalaryDataDao;
import com.boss.salary.dao.ISalaryPaymentTicketDao;
import com.boss.salary.entity.SalaryPaymentRequisitionBack;
import com.boss.salary.entity.SalaryPaymentTicket;
import com.boss.salary.service.ISalaryPaymentTicketService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.String.valueOf;

@Service
public class SalaryPaymentTicketServiceImpl implements ISalaryPaymentTicketService {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(SalaryPaymentTicketServiceImpl.class);
    @Autowired
    private ISalaryPaymentTicketDao dao;
    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private SalaryPaymentTicketServiceImpl salaryPaymentTicketService;
    @Autowired
    private IGenerateSalaryDataDao iGenerateSalaryDataDao;


    @Override
    public PageDTO<SalaryPaymentTicket> queryPaymentTicketPage(PaginationDTO paginationDTO,String mofDivCode,String agencyId,String flag, String agencyName, String payeeAcctNo, String payAppAmt, String payeeAcctName, String payeeAcctBankName) {
            List<SalaryPaymentTicket> paymentTicket = dao.queryPaymentTicketPage(paginationDTO,mofDivCode,agencyId,flag, agencyName, payeeAcctNo, payAppAmt, payeeAcctName, payeeAcctBankName);
            int total = dao.queryaymentTicket(mofDivCode,agencyId,flag,agencyName, payeeAcctNo, payAppAmt, payeeAcctName, payeeAcctBankName);
            PageDTO<SalaryPaymentTicket> pageDTO = new PageDTO<>();
            pageDTO.setRows(paymentTicket);
            pageDTO.setTotal(total);
            return pageDTO;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentTicket(SalaryPaymentTicket salaryPaymentTicket) {
        salaryPaymentTicket.setUpdateTime(valueOf(DateUtils.getCurrentTimeStamp()));
        dao.updatePaymentTicket(salaryPaymentTicket);
    }
    //批量插入
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map insertPaymentTicket(List<SalaryPaymentTicket> salaryPaymentTickets,String mofDivCode) {
        //通过传会来的 数据中的payId 去 sal_salary_payment_requisition_back 表中差数据
         List<SalaryPaymentTicket> salaryPaymentBanks=dao.salaryPaymentBank(salaryPaymentTickets,mofDivCode);
         Map<String,Object>map= new HashMap<>();
         //查看 返回数数据多少条处理了多少条
         map.put("100000","返回"+salaryPaymentTickets.size()+"条"+"处理"+salaryPaymentBanks.size()+"条");
         if(salaryPaymentBanks.size()>0 || null==salaryPaymentBanks ){
           List<SalaryPaymentTicket> addlist = new ArrayList<>();
             // 将查出来的数据循环
            for(SalaryPaymentTicket  salaryPaymentTicket :  salaryPaymentTickets){
                //将获取的数据循环
              for(SalaryPaymentTicket salaryPaymentBank:salaryPaymentBanks){
               //判断查出来的payId 和 传过来的 payId 是否相等
               if(salaryPaymentTicket.getPayId().equals(salaryPaymentBank.getPayId())){
                  salaryPaymentBank.setId(SysUtils.generateGuid());
                  salaryPaymentBank.setCreateTime(valueOf(DateUtils.getCurrentTimeStamp()));
                  salaryPaymentBank.setIsDeleted(1);
                  salaryPaymentBank.setIsPushAgain(0);
                  salaryPaymentBank.setReturnTime(salaryPaymentTicket.getRevisitReasonTime());
                  salaryPaymentBank.setReturnReason(salaryPaymentTicket.getReturnReason());
                  salaryPaymentBank.setPayAppAmt(salaryPaymentTicket.getPayAppAmt());
                  addlist.add(salaryPaymentBank);
                 }
               }
            }
            dao.insertPaymentTicket(addlist);
//            iGenerateSalaryDataDao.deleteBatchPayBack(salaryPaymentTickets,mofDivCode);//暂不处理原申请数据，存在部分退款问题，只做金额记录用
         }
            return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String modifyIsPushAgain(List<Map<String,Object>> mapList,UserDTO userDTO,String tokenid) {
        List<Map<String,Object>> payList=new ArrayList<>();
        for(Map map:mapList){
            Map<String,Object> payMap=new HashMap<>();
            payMap.put("agency_id",map.get("agencyId"));
            payMap.put("bgt_id",map.get("bgtId"));
            payMap.put("payee_acct_name",map.get("newPayeeAcctName"));
            payMap.put("payee_acct_no",map.get("newPayeeAcctNo"));
            payMap.put("payee_acct_bank_name",map.get("payeeAcctBankName"));
            payMap.put("amt",map.get("payAppAmt"));
            payMap.put("use_",map.get("useName"));
            payList.add(payMap);
        }
       String  toPayment=salaryPaymentTicketService.toPayment(payList,userDTO,tokenid);
        dao.modifyIsPushAgain(mapList);
        return toPayment;
    }


    //@Override
    public String toPayment(List<Map<String, Object>> payListOneAgency, UserDTO userDto,String tokenid){
        JSONArray jsonArray =new JSONArray();
        Map<String,String> map= iCommonService.sentPayMent(payListOneAgency, tokenid);//每个单位单独走数据
        JSONObject result = JSONObject.parseObject(map.get("result"));
        String rscode = result.getString("rscode");
        List<String> agencyIds=new ArrayList<>();//反写需要走工作流的单位id
        for(Map map1:payListOneAgency){
            agencyIds.add(map1.get("agency_id").toString());
        }

        // 调用成功
        if ("200".equals(rscode)) {//将成功的数据单位id保存在集合中，后续处理
            jsonArray.addAll(result.getJSONArray("data"));
            savePayBackDatas(jsonArray,userDto,agencyIds);// 保存回单数据
        } else {
            logger.info(result.getString("result"));
            throw new AppRuntimeException(result.getString("result"));
//            requestMessage.append("F-"+result.getString("result")+"\n");
        }
        return  result.getString("result");
    }

    /**
     * 保存支付回单数据
     * @param jsonArray
     */
    private void savePayBackDatas(JSONArray jsonArray, UserDTO userDto, List<String> agencyIds) {
        List<SalaryPaymentRequisitionBack> salaryPaymentRequisitionBacks=new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // 修改表状态，并添加模拟值
            String agencyId = jsonObject.getString("agency_id");
            SalaryPaymentRequisitionBack salaryPaymentRequisitionBack = new SalaryPaymentRequisitionBack();
            salaryPaymentRequisitionBack.setId(SysUtils.generateGuid());
            salaryPaymentRequisitionBack.setCreateTime(valueOf(DateUtils.getCurrentTimeStamp()));
            salaryPaymentRequisitionBack.setUpdateTime(valueOf(DateUtils.getCurrentTimeStamp()));
            salaryPaymentRequisitionBack.setAgencyId(agencyId);
            salaryPaymentRequisitionBack.setAgencyName(jsonObject.getString("agency_name"));
            salaryPaymentRequisitionBack.setPayId(jsonObject.getString("id"));
            salaryPaymentRequisitionBack.setPayAppNo(jsonObject.getString("pay_app_no"));
            salaryPaymentRequisitionBack.setBgtId(jsonObject.getString("bgt_id"));
            salaryPaymentRequisitionBack.setPayAppAmt(jsonObject.getString("pay_app_amt"));
            salaryPaymentRequisitionBack.setFundType(jsonObject.getString("fund_type"));
            salaryPaymentRequisitionBack.setPayeeAcctName(jsonObject.getString("payee_acct_name"));
            salaryPaymentRequisitionBack.setPayeeAcctNo(jsonObject.getString("payee_acct_no"));
            salaryPaymentRequisitionBack.setPayeeAcctBankName(jsonObject.getString("payee_acct_bank_name"));
            salaryPaymentRequisitionBack.setPayType(jsonObject.getString("pay_type"));
            salaryPaymentRequisitionBack.setProCat(jsonObject.getString("pro_cat"));
            salaryPaymentRequisitionBack.setGovBgtEco(jsonObject.getString("gov_bgt_eco"));
            salaryPaymentRequisitionBack.setDepBgtEco(jsonObject.getString("dep_bgt_eco"));
            salaryPaymentRequisitionBack.setPro(jsonObject.getString("pro"));
            salaryPaymentRequisitionBack.setUseName(jsonObject.getString("use_"));
            salaryPaymentRequisitionBack.setExpFunc(jsonObject.getString("exp_func"));
            salaryPaymentRequisitionBack.setMofDivCode(userDto.getProvince());
            salaryPaymentRequisitionBack.setIsDeleted(SystemDictConstant.IS_FALSE);
            salaryPaymentRequisitionBacks.add(salaryPaymentRequisitionBack);
        }
       iGenerateSalaryDataDao.batchInsertPayBackData(salaryPaymentRequisitionBacks);
    }


}
